package game;

import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

public class MusicPlayer implements Runnable {
	public boolean playing;		// Music player status, true if on, false if off

	/**
	 * Constructor of MusicPlayer
	 */
	public MusicPlayer() {
		playing = true;
	}

	/**
	 * Stop playing music
	 */
	public void stopPlay() {
		playing = false;
	}

	/**
	 * Start music playing
	 * @param fileName
	 * @return
	 */
	private Clip play(String fileName) {
		try {
			// Read music file
			InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
			AudioInputStream a = AudioSystem.getAudioInputStream(inputStream);
			AudioFormat format = a.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, format);
			Clip clip = (Clip) AudioSystem.getLine(info);
			// Open music file
			clip.open(a);
			// Set volumen value
			FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
			gainControl.setValue(-10);
			// Start music
			clip.start();
			return clip;
		} catch(Exception e) {
			System.out.println(e);
		}
		return null;
	}

	/**
	 * Thread for MusicPlayer
	 */
	@Override
	public void run() {
		String song = "audio/song.wav";
		Clip c = play(song);
		while(playing) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} 
		}
		c.stop();
	}
}
